if(!function_exists('catch_first_image')) {
    function catch_first_image() {
    	global $post, $posts;
		$first_img = '';
		ob_start();
		ob_end_clean();
		$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content,$matches);
		$first_img = $matches [1] [0];
		return $first_img;
   } 
}

function post_to_sina_weibo($post_ID) {
   if (wp_is_post_revision($post_ID)) return;  //修订版本(更新)不发微博
   $get_post_info = get_post($post_ID);
   $get_post_centent = get_post($post_ID)->post_content;
   $get_post_title = get_post($post_ID)->post_title;
   if ($get_post_info->post_status == 'publish' && $_POST['original_post_status'] != 'publish') {
       $appkey='1125374965';  //此处是你的新浪微博appkey，不修改的话就会显示来自Share Ykuaile哦！]
       $username='你的新浪微博用户名';
       $userpassword='你的新浪微博账户密码';
       $request = new WP_Http;
       $keywords = ""; 
 
       //获取文章标签关键词
       $tags = wp_get_post_tags($post_ID);
       foreach ($tags as $tag ) {
          $keywords = $keywords.'#'.$tag->name."#";
       }
 
       //修改了下风格，并添加文章关键词作为微博话题，提高与其他相关微博的关联率

     
       //获取特色图片，如果没设置就抓取文章第一张图片 
       if (has_post_thumbnail()) {
          $image_src = wp_get_attachment_image_src( get_post_thumbnail_id($post_ID), 'large');
     	  $url = $image_src[0];
       //抓取第一张图片作为特色图片，可替换成主题函数支持
       } else if(function_exists('catch_first_image')) {
          $url = catch_first_image(); 
       }
       //判断是否存在图片，定义不同的接口
       $status = '【文章发布】' . strip_tags( $get_post_title ).'：'.mb_strimwidth(strip_tags( apply_filters('the_content', $get_post_centent)),0, 132,'...') .$keywords. ' 查看全文:' . get_permalink($post_ID) ;
       if(!empty($url)){
           $api_url = 'https://api.weibo.com/2/statuses/upload_url_text.json'; //新的API接口地址
           $body = array('status' => $status,'source' => $appkey,'url' => $url);
       } else {
           $api_url = 'https://api.weibo.com/2/statuses/update.json';
           $body = array('status' => $status,'source' => $appkey);
       }

       $headers = array('Authorization' => 'Basic ' . base64_encode("$username:$userpassword"));
       $result = $request->post($api_url, array('body' => $body,'headers' => $headers));
 
    }
}
add_action('publish_post', 'post_to_sina_weibo', 0);